<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>分类管理</title>
		<link rel="stylesheet" href="../layui/css/layui.css">
		<link rel="stylesheet" href="../css/index.css">
		<script src="../js/authChecker.js"></script>
		<style>
			.category-container {
				padding: 20px;
			}

			.category-table {
				width: 100%;
				border-collapse: collapse;
				margin-top: 20px;
			}

			.category-table th,
			.category-table td {
				border: 1px solid #ccc;
				padding: 10px;
				text-align: center;
			}

			.category-table th {
				background-color: #d8d8d9;
				color: black;
				font-weight: bold;
			}

			.category-table tr:nth-child(even) {
				background-color: #f9f9f9;
			}

			.category-table tr:hover {
				background-color: #f1f1f1;
			}

			.category-actions {
				display: flex;
				justify-content: center;
				gap: 5px;
			}

			.category-form-item {
				margin-bottom: 15px;
			}

			.layui-card-header {
				font-size: 22px;
				color: #333;
				margin-bottom: 20px;
				font-weight: 600;
			}

			/* 列宽分配 */
			.category-table th:nth-child(1),
			.category-table td:nth-child(1) {
				width: 15%;
			}

			.category-table th:nth-child(2),
			.category-table td:nth-child(2) {
				width: 20%;
			}

			.category-table th:nth-child(3),
			.category-table td:nth-child(3) {
				width: 30%;
			}

			.category-table th:nth-child(4),
			.category-table td:nth-child(4) {
				width: 20%;
			}

			.category-table th:nth-child(5),
			.category-table td:nth-child(5) {
				width: 15%;
			}

			/* 按钮样式 */
			#addCategory {
				background-color: #FF1493;
				color: white;
			}

			.category-icon-preview {
				width: 100px;
				height: 100px;
				object-fit: contain;
				border: 1px solid #eee;
				margin-top: 10px;
			}

			/* 搜索框样式 */
			.search-container {
				display: flex;
				margin-bottom: 20px;
			}

			.search-input {
				flex: 1;
				margin-right: 10px;
			}

			/* 操作按钮样式 */
			.action-btn {
				padding: 0 8px;
				height: 28px;
				line-height: 28px;
				font-size: 12px;
				min-width: 60px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				background: none;
				border: 1px solid #d8d8d9;
				color: #333;
				cursor: pointer;
			}

			.action-btn:hover {
				background-color: #f1f1f1;
			}
		</style>
	</head>
	<body>
		<div class="category-container">
			<div class="layui-row layui-col-space15">
				<div class="layui-col-md12">
					<div class="layui-card">
						<div class="layui-card-header">分类管理</div>
						<div class="layui-card-body">
							<div class="search-container">
								<div class="layui-input-block search-input">
									<input type="text" id="searchInput" placeholder="请输入分类名称" class="layui-input">
								</div>
								<button class="layui-btn layui-btn-primary" id="searchBtn">
									<i class="layui-icon">&#xe615;</i> 搜索
								</button>
								<button class="layui-btn" id="addCategory">
									<i class="layui-icon">&#xe654;</i> 添加分类
								</button>
								<button class="layui-btn layui-btn-primary" id="refreshBtn">
									<i class="layui-icon">&#x1002;</i> 刷新
								</button>
							</div>
						</div>
					</div>
				</div>

				<!-- 分类列表表格 -->
				<table class="category-table" id="categoryTable">
					<thead>
						<tr>
							<th>分类ID</th>
							<th>分类名称</th>
							<th>分类描述</th>
							<th>分类图标</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody>
						<!-- 动态内容将通过JS填充 -->
					</tbody>
				</table>

				<!-- 分页控件 -->
				<div id="pagination" style="text-align: center; margin-top: 20px;"></div>
			</div>
		</div>

		<!-- 添加分类的弹窗 -->
		<div id="addCategoryDialog" style="display: none; padding: 20px;">
			<form class="layui-form" lay-filter="addCategoryForm">
				<div class="category-form-item">
					<label class="layui-form-label">分类名称</label>
					<div class="layui-input-block">
						<input type="text" name="categoryname" required lay-verify="required" placeholder="请输入分类名称"
							autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="category-form-item">
					<label class="layui-form-label">分类描述</label>
					<div class="layui-input-block">
						<textarea name="categorydesc" placeholder="请输入分类描述" class="layui-textarea"></textarea>
					</div>
				</div>
				<div class="category-form-item">
					<label class="layui-form-label">分类图标</label>
					<div class="layui-input-block">
						<button type="button" class="layui-btn" id="addUploadBtn">
							<i class="layui-icon">&#xe67c;</i>上传图片
						</button>
						<div class="layui-upload-list">
							<img class="category-icon-preview" id="addPreviewImg" style="display: none;">
						</div>
					</div>
				</div>
			</form>
		</div>

		<!-- 编辑分类的弹窗 -->
		<div id="editCategoryDialog" style="display: none; padding: 20px;">
			<form class="layui-form" lay-filter="editCategoryForm">
				<input type="hidden" name="id">
				<div class="category-form-item">
					<label class="layui-form-label">分类ID</label>
					<div class="layui-input-block">
						<input type="text" name="categoryid" disabled autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="category-form-item">
					<label class="layui-form-label">分类名称</label>
					<div class="layui-input-block">
						<input type="text" name="categoryname" required lay-verify="required" placeholder="请输入分类名称"
							autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="category-form-item">
					<label class="layui-form-label">分类描述</label>
					<div class="layui-input-block">
						<textarea name="categorydesc" placeholder="请输入分类描述" class="layui-textarea"></textarea>
					</div>
				</div>
				<div class="category-form-item">
					<label class="layui-form-label">分类图标</label>
					<div class="layui-input-block">
						<button type="button" class="layui-btn" id="editUploadBtn">
							<i class="layui-icon">&#xe67c;</i>上传图片
						</button>
						<div class="layui-upload-list">
							<img class="category-icon-preview" id="editPreviewImg" style="display: none;">
						</div>
					</div>
				</div>
			</form>
		</div>

		<script src="../js/jquery3.5.1.js"></script>
		<script src="../layui/layui.js"></script>
		<script>
			// 在页面加载时立即检查登录状态
			if (!checkAdminLogin()) {
				// 登录检查失败，阻止页面继续加载
				console.log('登录验证失败，已跳转至登录页');
			} else {
				layui.use(['form', 'layer', 'upload', 'laypage'], function() {
					var form = layui.form;
					var layer = layui.layer;
					var upload = layui.upload;
					var laypage = layui.laypage;
					var $ = layui.$;

					// 全局变量
					var currentPage = 1;
					var pageSize = 10;
					var searchKeyword = '';

					// 新增分类状态
					let addStatus = {
						isUploaded: false,
						imageUrl: ''
					};

					// 编辑分类状态
					let editStatus = {
						currentId: '',
						isUploaded: false,
						imageUrl: ''
					};

					// 初始化新增上传组件
					upload.render({
						elem: '#addUploadBtn',
						url: 'http://localhost:8887/upload/categoryImage',
						size: 10240, // 10MB限制
						accept: 'images',
						acceptMime: 'image/*',
						done: function(res) {
							if (res.code === 200) {
								$('#addPreviewImg').attr('src', res.data.url).show();
								addStatus.imageUrl = res.data.url;
								addStatus.isUploaded = true;
								layer.msg('图片上传成功', {
									icon: 1
								});
							} else {
								addStatus.isUploaded = false;
								layer.msg(res.msgerr || '上传失败', {
									icon: 2
								});
							}
						},
						error: function() {
							layer.msg('上传失败，请稍后重试', {
								icon: 2
							});
						}
					});

					// 初始化编辑上传组件
					upload.render({
						elem: '#editUploadBtn',
						url: 'http://localhost:8887/upload/categoryHandle',
						data: {
							id: function() {
								return editStatus.currentId;
							},
							categoryname: function() {
								return $('#editCategoryDialog input[name="categoryname"]').val();
							}
						},
						done: function(res) {
							if (res.code === 200) {
								$('#editPreviewImg').attr('src', res.data.url).show();
								editStatus.imageUrl = res.data.url;
								editStatus.isUploaded = true;
								layer.msg('图片上传成功', {
									icon: 1
								});
							} else {
								editStatus.isUploaded = false;
								layer.msg(res.msgerr || '上传失败', {
									icon: 2
								});
							}
						},
						error: function() {
							layer.msg('上传失败，请稍后重试', {
								icon: 2
							});
						}
					});

					// 加载分类列表
					function loadCategories(page, keyword) {

						var url = 'http://localhost:8887/category/seCaByCaName';
						var params = {
							page: page || 1,
							pageSize: pageSize
						};

						if (keyword && keyword.trim() !== '') {
							url = 'http://localhost:8887/category/seCaByCaName';
							params.categoryName = keyword;
						}

						$.ajax({
							url: url,
							type: 'GET',
							data: params,
							dataType: 'json',
							success: function(res) {

								if (res.code === 200) {
									renderCategoryList(res.data.listCategory || res.data.snacksPageInfo
									.list);
									renderPagination(res.data.snacksPageInfo.total, page || 1);
								} else {
									layer.msg(res.msgerr || '获取分类列表失败', {
										icon: 2
									});
								}
							},
							error: function(xhr) {
								layer.closeAll('loading');
								var errorMsg = '加载分类列表失败';
								try {
									var errRes = JSON.parse(xhr.responseText);
									errorMsg = errRes.msgerr || errorMsg;
								} catch (e) {}
								layer.msg(errorMsg, {
									icon: 2
								});
							}
						});
					}

					// 渲染分类列表
					function renderCategoryList(categories) {
						categories = Array.isArray(categories) ? categories : [];
						var html = '';
						categories.forEach(function(category) {
							let imageUrl = category.categoryicon || '../img/default-category.png';

							html += `
                        <tr>
                            <td>${category.categoryid || '--'}</td>
                            <td>${category.categoryname || '--'}</td>
                            <td>${category.categorydesc || '--'}</td>
                            <td>
                                <img src="${imageUrl}" 
                                    onerror="this.src='../img/default-category.png'" 
                                    style="max-width: 38px; max-height: 38px;">
                            </td>
                            <td style="overflow: hidden; white-space: nowrap; padding: 5px;">
                                <div style="display: flex; justify-content: center; gap: 5px; flex-wrap: nowrap; max-width: 100%;">
                                    <button class="action-btn edit-category" data-id="${category.categoryid}">
                                        <i class="layui-icon" style="font-size: 14px;">&#xe642;</i>编辑
                                    </button>
                                    <button class="action-btn delete-category" data-id="${category.categoryid}">
                                        <i class="layui-icon" style="font-size: 14px;">&#xe640;</i>删除
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `;
						});

						$('#categoryTable tbody').html(html);

						// 绑定编辑和删除事件
						$('.edit-category').on('click', function() {
							var categoryId = $(this).data('id');
							editCategory(categoryId);
						});

						$('.delete-category').on('click', function() {
							var categoryId = $(this).data('id');
							deleteCategory(categoryId);
						});
					}

					// 渲染分页
					function renderPagination(total, curr) {
						laypage.render({
							elem: 'pagination',
							count: total,
							curr: curr,
							limit: pageSize,
							layout: ['count', 'prev', 'page', 'next', 'skip'],
							jump: function(obj, first) {
								if (!first) {
									currentPage = obj.curr;
									loadCategories(currentPage, searchKeyword);
								}
							}
						});
					}

					// 添加分类
					$('#addCategory').on('click', function() {
						resetAddForm();
						layer.open({
							type: 1,
							title: '添加新分类',
							area: ['600px', '450px'],
							content: $('#addCategoryDialog'),
							btn: ['确认添加', '取消'],
							yes: function(index) {
								var categoryname = $('#addCategoryDialog input[name="categoryname"]')
									.val().trim();
								var categorydesc = $(
										'#addCategoryDialog textarea[name="categorydesc"]').val()
									.trim();

								if (!categoryname) {
									layer.msg('请输入分类名称', {
										icon: 2
									});
									return;
								}

								if (!addStatus.isUploaded) {
									layer.msg('请上传分类图标', {
										icon: 2
									});
									return;
								}

								// 提交数据到分类接口
								$.ajax({
									url: 'http://localhost:8887/category/insertCategory',
									type: 'POST',
									contentType: 'application/json',
									data: JSON.stringify({
										categoryname: categoryname,
										categorydesc: categorydesc,
										categoryicon: addStatus.imageUrl
									}),
									success: function(res) {
										if (res.code === 200) {
											layer.msg('添加成功', {
												icon: 1
											});
											loadCategories(currentPage, searchKeyword);
											layer.close(index);
											resetAddForm();
										} else {
											layer.msg(res.msgerr || '添加失败', {
												icon: 2
											});
										}
									},
									error: function() {
										layer.msg('请求失败，请稍后重试', {
											icon: 2
										});
									}
								});
							},
							cancel: function() {
								resetAddForm();
							}
						});
					});

					// 编辑分类
					function editCategory(categoryId) {
						layer.load(1);

						$.ajax({
							url: 'http://localhost:8887/category/' + categoryId,
							type: 'GET',
							dataType: 'json',
							success: function(res) {
								layer.closeAll('loading');

								// 修正判断条件：直接检查分类对象是否存在（通过categoryid判断）
								if (res && res.categoryid) {
									var category = res; // 响应根节点就是分类数据
									editStatus.currentId = category.categoryid;

									// 填充表单数据
									form.val('editCategoryForm', {
										id: category.categoryid,
										categoryid: category.categoryid,
										categoryname: category.categoryname,
										categorydesc: category.categorydesc
									});

									// 处理分类图标显示
									if (category.categoryicon) {
										$('#editPreviewImg').attr('src', category.categoryicon).show();
										editStatus.imageUrl = category.categoryicon;
										editStatus.isUploaded = true;
									} else {
										$('#editPreviewImg').attr('src', '').hide();
										editStatus.isUploaded = false;
									}

									// 打开编辑弹窗
									layer.open({
										type: 1,
										title: '编辑分类',
										area: ['600px', '450px'],
										content: $('#editCategoryDialog'),
										btn: ['保存修改', '取消'],
										yes: function(index) {
											var categoryname = $(
												'#editCategoryDialog input[name="categoryname"]'
												).val().trim();
											var categorydesc = $(
												'#editCategoryDialog textarea[name="categorydesc"]'
												).val().trim();

											// 验证必填项
											if (!categoryname) {
												layer.msg('请输入分类名称', {
													icon: 2
												});
												return;
											}
											if (!editStatus.currentId) {
												layer.msg('分类ID不存在', {
													icon: 2
												});
												return;
											}

											// 构造请求数据（确保字段名与后端实体一致）
											var updateData = {
												categoryid: editStatus.currentId, // 必传
												categoryname: categoryname, // 必传
												categorydesc: categorydesc ||
												'', // 可选，为空时传空字符串
												categoryicon: editStatus.imageUrl ||
													'' // 确保即使未上传图片也传递字段
											};

											$.ajax({
												url: 'http://localhost:8887/category/updateCategoryend',
												type: 'POST',
												contentType: 'application/json',
												data: JSON.stringify(updateData),
												success: function(res) {
													// 根据后端Rep格式判断
													if (res.code === 200) {
														layer.msg('修改成功', {
															icon: 1
														});
														loadCategories(currentPage,
															searchKeyword); // 刷新列表
														layer.close(index); // 关闭弹窗
													} else {
														layer.msg(res.msgerr ||
															'修改失败', {
																icon: 2
															});
													}
												},
												error: function() {
													layer.msg('请求失败，请稍后重试', {
														icon: 2
													});
												}
											});
										},
										cancel: function() {
											resetEditForm();
										}
									});
								} else {
									// 只有当响应中没有分类ID时才显示失败
									layer.msg('获取分类信息失败', {
										icon: 2
									});
								}
							},
							error: function() {
								layer.closeAll('loading');
								layer.msg('请求失败，请稍后重试', {
									icon: 2
								});
							}
						});
					}

					// 删除分类
					function deleteCategory(categoryId) {
						layer.confirm('确定要删除这个分类吗？', {
							icon: 3,
							title: '提示'
						}, function(index) {
							layer.load(1);

							$.ajax({
								url: 'http://localhost:8887/category/' + categoryId,
								type: 'DELETE',
								success: function(res) {
									layer.closeAll();

									if (res.code === 200) {
										layer.msg('删除成功', {
											icon: 1
										});
										loadCategories(currentPage, searchKeyword);
									} else {
										layer.msg(res.msgerr || '删除失败', {
											icon: 2
										});
									}
								},
								error: function() {
									layer.closeAll('loading');
									layer.msg('删除失败，请稍后重试', {
										icon: 2
									});
								}
							});
						});
					}

					// 搜索分类
					$('#searchBtn').on('click', function() {
						searchKeyword = $('#searchInput').val().trim();
						currentPage = 1;
						loadCategories(currentPage, searchKeyword);
					});

					// 重置搜索
					$('#refreshBtn').on('click', function() {
						$('#searchInput').val('');
						searchKeyword = '';
						currentPage = 1;
						loadCategories(currentPage, searchKeyword);
					});

					// 重置表单
					function resetAddForm() {
						$('#addCategoryDialog input[name="categoryname"]').val('');
						$('#addCategoryDialog textarea[name="categorydesc"]').val('');
						$('#addPreviewImg').attr('src', '').hide();
						addStatus = {
							isUploaded: false,
							imageUrl: ''
						};
					}

					function resetEditForm() {
						$('#editCategoryDialog input[name="categoryname"]').val('');
						$('#editCategoryDialog textarea[name="categorydesc"]').val('');
						$('#editCategoryDialog input[name="id"]').val('');
						$('#editPreviewImg').attr('src', '').hide();
						editStatus = {
							currentId: '',
							isUploaded: false,
							imageUrl: ''
						};
					}

					// 初始化加载分类列表
					loadCategories(currentPage, searchKeyword);
				});
			}
		</script>
	</body>
</html>